import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:gold/http/apis.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/gold_price_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/ui/home/rank/rank_content_viewmodel.dart';
import 'package:gold/utils/size_extension.dart';
import 'package:gold/utils/xfg_extension.dart';

import 'geocode/geocode_entity.dart';
import 'geocode/geocode_util.dart';

/// @description:
/// @author tangzhentao
/// @created at 18:43 2024/11/24
///

/// 实时金价key
final realTimeGoldPrice = '1301';

/// 测量文字宽度
Size xfgBoundingTextSize(String text, {TextStyle style = const TextStyle(),int maxLines = 2^31, double maxWidth = double.infinity}) {
  if (text.isEmpty) {
    return Size.zero;
  }

  final TextPainter textPainter = TextPainter(
      textDirection: TextDirection.ltr,
      text: TextSpan(text: text, style: style), maxLines: maxLines)
    ..layout(maxWidth: maxWidth);
  return textPainter.size;
}

/// 先锋金独有打印
void xfgPrint(Object? object) {
  if (true) {
    print.call(object);
  }
}

/// 正则匹配验证手机号
final RegExp _exp = RegExp(r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');

/// 是否手机号
bool isPhone(String value) => _exp.hasMatch(value);

/// 排行榜时间描述
String rankTimeDesc(PoolType type) {
  switch (type) {
    case PoolType.day:
      return '025/07/30\n12:30:35';
    case PoolType.week:
      return '2025/07/23\n2025/07/30';
    case PoolType.month:
      return '2025/07';
    case PoolType.year:
      return '2025';
  }
}

/// 获取星期几
String getWeekday(int weekDay) {
  switch (weekDay) {
    case DateTime.monday:
      return '周一';
    case DateTime.tuesday:
      return '周二';
    case DateTime.wednesday:
      return '周三';
    case DateTime.thursday:
      return '周四';
    case DateTime.friday:
      return '周五';
    case DateTime.saturday:
      return '周六';
    default:
      return '周日';
  }
}

/// 获取文件或文件夹大小
Future<int> getTotalSizeOfDirectory(FileSystemEntity file) async {
  if (!(await file.exists())) return 0;
  if (file is File) {
    return await file.length();
  } else if (file is Directory) {
    final children = file.listSync();
    int total = 0;
    if (children.isNotEmpty) {
      for (FileSystemEntity child in children) {
        total += await getTotalSizeOfDirectory(child);
      }
    }
    return total;
  } else {
    return 0;
  }
}

/// 递归删除文件或文件夹
Future deleteDirectory(FileSystemEntity file, {bool isDeleteDirectory = false}) async {
  if (!file.existsSync()) return;
  if (file is Directory) {
    final children = file.listSync();
    for (FileSystemEntity child in children) {
      await deleteDirectory(child, isDeleteDirectory: true);
    }
    if (isDeleteDirectory) await file.delete();
  } else {
    await file.delete();
  }
}

/// 压缩图片
Future<Uint8List> compressImage(Uint8List image, {
  int minWidth = 1920,
  int minHeight = 1080,
  int inSampleSize = 1,
  int quality = 75,
  int rotate = 0,
  bool autoCorrectionAngle = true,
  CompressFormat format = CompressFormat.jpeg,
  bool keepExif = false,
  int numberOfRetries = 5,
}) async {
  xfgPrint.call('原大小: ${image.length.storage}');
  final data = await FlutterImageCompress.compressWithList(image, minWidth: minWidth, minHeight: minHeight, quality: quality);
  xfgPrint.call('压缩后大小: ${data.length.storage}');
  return data;
}

/// 去黄金回收页面
Future<dynamic> toGoldRecovery({bool replace = false}) async {
  final result = await Http().request<GoldPriceModel>(Apis.goldPrice, data: {'goldid': '1301'}, loadingText: '获取实时金价...');
  if (result.success) {
    double? price = double.tryParse(result.data?.result?.dtList?[realTimeGoldPrice]?.lastPrice?? '');
    if (price != null && price > 0) {
      if (replace) {
        return await XfgNav.pushReplacementNamed(Routes.goldRecover, arguments: price);
      } else {
        return await XfgNav.pushNamed(Routes.goldRecover, arguments: price);
      }
    } else {
      '金价获取失败，请稍后重试'.error();
      return null;
    }
  } else {
    return null;
  }
}

/// 经纬度地理反编码
Future<GeocodeEntity> geocodeCoordinate(double lat, double lon, {String pathHead = 'assets/'}) async {
  final res = await GeocodeUtil.geocodeGPS(lat, lon, pathHead: pathHead);
  return res;
}